import { useUserStore } from '@/stores/user'
import { createRouter, createWebHistory } from 'vue-router'

// 创建路由器
const router = createRouter({
  // 路由模式
  history: createWebHistory(import.meta.env.BASE_URL),
  // 路由规则
  routes: [
    {
      path: '/',
      name: 'index',
      meta: { keepAlive: true },
      redirect: '/films',
      component: () => import('@/views/index.vue'),
      children: [
        {
          path: 'films',
          name: 'films',
          component: () => import('@/views/index/films.vue')
        },
        {
          path: 'cinemas',
          name: 'cinemas',
          meta: { keepAlive: true },
          component: () => import('@/views/index/cinemas.vue')
        },
        {
          path: 'active',
          name: 'active',
          component: () => import('@/views/index/active.vue')
        },
        {
          path: 'center',
          name: 'center',
          component: () => import('@/views/index/center.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login.vue')
    },
    {
      path: '/user-order',
      name: 'user-order',
      meta: { needLogin: true },
      component: () => import('@/views/user-order.vue')
    },
    {
      path: '/user-red',
      name: 'user-red',
      meta: { needLogin: true },
      component: () => import('@/views/user-red.vue')
    },
    {
      path: '/film/:id',
      name: 'film',
      component: () => import('@/views/film.vue')
    },
    {
      path: '/city',
      name: 'city',
      component: () => import('@/views/city.vue'),
      meta: {
        keepAlive: true
      }
    },
    {
      path: '/cinemas/search',
      name: 'cinemas-search',
      component: () => import('@/views/cinemas-search/index.vue')
    },
    {
      path: '/cinema/:id/film/:filmId?/:date?',
      name: 'schedule',
      component: () => import('@/views/schedule/index.vue')
    }
  ]
})

router.beforeEach((to) => {
  const { userInfo } = storeToRefs(useUserStore())

  if (to.meta.needLogin && !userInfo.value) {
    // 打到登录
    return {
      name: 'login',
      query: { redirect: to.fullPath }
    }
  }
})

export default router
